package com.ahdy.controller;

import com.ahdy.entity.MedicalRecordAnalysis;
import com.ahdy.service.MedicalRecordAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Date;

/**
 * 病历分析记录控制器
 */
@RestController
@RequestMapping("/api/medical-record-analysis")
public class MedicalRecordAnalysisController {

    @Autowired
    private MedicalRecordAnalysisService medicalRecordAnalysisService;

    /**
     * 上传病历图片并进行分析
     *
     * @param elderlyId 老人ID
     * @param file      病历图片文件
     * @return 分析结果
     */
    @PostMapping("/upload-analyze")
    public ResponseEntity<?> uploadAndAnalyze(@RequestParam Integer elderlyId,
            @RequestParam("file") MultipartFile file) {
        try {
            // 保存图片
            String imagePath = saveImage(file);

            // 分析并保存结果
            MedicalRecordAnalysis result = medicalRecordAnalysisService.analyzeAndSave(elderlyId, imagePath);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "上传并分析成功");
            response.put("data", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "上传或分析失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 直接保存文本形式的病历分析结果
     *
     * @param elderlyId       老人ID
     * @param analysisResult  分析结果
     * @param recommendation  康复建议
     * @param relatedDiseases 相关疾病，多个疾病用逗号分隔
     * @param imagePath       图片路径（可选）
     * @return 保存结果
     */
    @PostMapping("/save-text-analysis")
    public ResponseEntity<?> saveTextAnalysis(@RequestParam Integer elderlyId,
            @RequestParam(required = false) String analysisResult,
            @RequestParam String recommendation,
            @RequestParam(required = false) String relatedDiseases,
            @RequestParam(required = false) String imagePath) {
        try {
            // 创建病历分析记录
            MedicalRecordAnalysis record = new MedicalRecordAnalysis();
            record.setElderlyId(elderlyId);
            record.setUploadDate(new Date());
            record.setAnalysisResult(analysisResult);
            record.setRecommendation(recommendation);
            record.setRelatedDiseases(relatedDiseases);
            record.setStatus("已分析");
            record.setAnalysisTime(new Date());
            record.setCreatedAt(new Date());
            record.setUpdatedAt(new Date());
            // 设置image_path的值，如果没有提供则使用默认值
            record.setImagePath(imagePath != null ? imagePath : "无图片记录");

            // 保存记录
            Integer recordId = medicalRecordAnalysisService.add(record);
            record.setId(recordId);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "保存分析结果成功");
            response.put("data", record);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "保存分析结果失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取病历分析列表（分页）
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @param status   状态（可选）
     * @return 分页结果
     */
    @GetMapping("/list")
    public ResponseEntity<?> list(@RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status) {
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        if (status != null && !status.isEmpty()) {
            params.put("status", status);
        }

        Map<String, Object> result = medicalRecordAnalysisService.page(params);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取列表成功");
        response.put("data", result);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据老人ID获取病历分析记录
     *
     * @param elderlyId 老人ID
     * @return 病历分析记录列表
     */
    @GetMapping("/elderly/{elderlyId}")
    public ResponseEntity<?> getByElderlyId(@PathVariable Integer elderlyId) {
        List<MedicalRecordAnalysis> list = medicalRecordAnalysisService.getByElderlyId(elderlyId);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取成功");
        response.put("data", list);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据ID获取病历分析记录详情
     *
     * @param id 记录ID
     * @return 病历分析记录
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getById(@PathVariable Integer id) {
        MedicalRecordAnalysis record = medicalRecordAnalysisService.getById(id);

        if (record == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 404);
            response.put("message", "记录不存在");
            return ResponseEntity.status(404).body(response);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取成功");
        response.put("data", record);
        return ResponseEntity.ok(response);
    }

    /**
     * 删除病历分析记录
     *
     * @param id 记录ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable Integer id) {
        boolean success = medicalRecordAnalysisService.delete(id);

        Map<String, Object> response = new HashMap<>();
        if (success) {
            response.put("code", 200);
            response.put("message", "删除成功");
        } else {
            response.put("code", 404);
            response.put("message", "记录不存在或删除失败");
            return ResponseEntity.status(404).body(response);
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 保存图片文件
     *
     * @param file 图片文件
     * @return 保存后的文件路径
     * @throws IOException 保存失败时抛出异常
     */
    private String saveImage(MultipartFile file) throws IOException {
        // 确保目录存在
        String uploadDir = "uploads/medical-records";
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        Path filePath = uploadPath.resolve(filename);
        Files.copy(file.getInputStream(), filePath);

        // 返回相对路径
        return uploadDir + "/" + filename;
    }
}
